<?php

namespace Frontend;

/**
 * Description of VideosController
 *
 * @author dung
 */

use BaseController;
use Config;
use Input;
use MyModel;
use Redirect;
use Sentry;
use Str;
use Validator;
use View;
use Jinput;
use App;
use Video;
use DInput;

class VideosController extends BaseController
{
    //put your code here

    public function __construct()
    {
        $this->beforeFilter('auth', array('only' => 'getCreate', 'postCreate', 'getEdit', 'postEdit'));
    }

    public function getIndex()
    {
        $data = array();
        $order = DInput::get('order', '', 'strip');
        $tone = DInput::get('tone', '', 'number');
        $topic = DInput::get('topic', '', 'number');
        $category = DInput::get('category', '', 'number');
        $key = DInput::get('key', '', 'strip');
        $vc = DInput::get('vc', '', 'number');
//        $order = Input::get('order', '');
//        $tone = is_numeric(Input::get('tone', '')) ? Input::get('tone', '') : '';
//        $topic = is_numeric(Input::get('topic', '')) ? Input::get('topic', '') : '';
//        $category = is_numeric(Input::get('category', '')) ? Input::get('category', '') : '';
//        $key = Input::get('key', '');
//        $vc = is_numeric(Input::get('vc')) ? Input::get('vc') : '';

        switch ($order) {
            case 'views':
                $data['orders']['field'] = 'videos.views';
                $data['paginate']['appends']['order'] = 'views';
                break;
            case 'thanks':
                $data['orders']['field'] = 'videos.thanks';
                $data['paginate']['appends']['order'] = 'thanks';
                break;
            default :
                $data['orders']['field'] = 'videos.id';
                $data['paginate']['appends']['order'] = 'id';
                break;
        }
        $data['orders']['type'] = 'DESC';
        $data['joins'][] = array('table' => 'users', 'pk' => 'users.id', 'fk' => 'videos.user_id');
        $data['conditions'][] = array('field' => 'videos.status', 'opr' => '=', 'value' => 'published');
        if ($tone != '') {
            $data['conditions'][] = array('field' => 'videos.tone_id', 'opr' => '=', 'value' => $tone);
            $data['paginate']['appends']['tone'] = $tone;
        }

        if ($category != '') {
            $data['conditions'][] = array('field' => 'videos.category_id', 'opr' => '=', 'value' => $category);
            $data['paginate']['appends']['category'] = $category;
        }

        if ($topic != '') {
            $data['joins'][] = array('table' => 'topicables', 'pk' => 'videos.id', 'fk' => 'topicables.video_id');
            $data['conditions'][] = array('field' => 'topicables.topic_id', 'opr' => '=', 'value' => $topic);
            $data['paginate']['appends']['topic'] = $topic;
        }

        if ($key != '') {
            $data['conditions'][] = array('field' => 'videos.title', 'opr' => 'LIKE', 'value' => '%' . $key . '%');
            $data['paginate']['appends']['key'] = $key;
        }
        if ($vc != '') {
            $data['conditions'][] = array('field' => 'videos.vcategory_id', 'opr' => '=', 'value' => $vc);
            $data['paginate']['appends']['vc'] = $vc;
        }
        $myModel = new \MyModel();
        $data['paginate']['nums'] = 20;
        $data['selects'] = array('videos.*', 'username');
        $data['videos'] = $myModel->listItems('Video', $data);

//        $data['tones'] = \Tone::leftJoin('videos', 'tones.id', '=', 'videos.tone_id')
//            ->select('tones.*', \DB::raw('count(videos.id) as videos'))
//            ->where('tones.status', '=', 'on')
//            ->groupBy('tones.id')
//            ->get();

//        $data['topics'] = $myModel->listAllItems('Topic');
//        $data['categories'] = $myModel->listAllItems('Category');
        return View::make('frontend/videos/index', compact('data'));
    }

    public function getDetail($id, $slug)
    {
        if (is_null($data['video'] = \Video::find($id)))
            return App::abort('404');
        $data['user'] = $data['video']->user()->first();
        $data['c_videos'] = Video::join('users', 'users.id', '=', 'videos.user_id')
            ->where('videos.category_id', '=', $data['video']->category_id)
            ->select('videos.*', 'users.username')->take(5)->get();
        $data['u_videos'] = Video::leftJoin('categories', 'categories.id', '=', 'videos.category_id')
            ->where('videos.user_id', '=', $data['video']->user_id)
            ->select('videos.*', 'categories.title as category_title')->take(5)->get();
        $data['t_videos'] = Video::leftJoin('users', 'users.id', '=', 'videos.user_id')
            ->where('videos.tone_id', '=', $data['video']->tone_id)
            ->leftJoin('categories', 'categories.id', '=', 'videos.category_id')
            ->select('videos.*', 'categories.title as category_title', 'users.username')->take(5)->get();

        $data['favourited'] = 'login';

        if (Sentry::check())
            $data['favourited'] = $data['video']->favourites()->where('user_id', '=', Sentry::getUser()->id)->count() > 0 ? 'favourite_active' : 'favourite';

        return View::make('frontend/videos/details', compact('data'));

    }

    public function getCreate()
    {
        $data = array();
        $myModel = new MyModel();
        $data['video'] = new \Video();
        $data['topics'] = \Topic::returnArray();
        $data['categories'] = $myModel->listAllItemsToArray('Category', array('value' => 'id', 'display' => 'title'));
        $data['tones'] = $myModel->listAllItemsToArray('Tone', array('value' => 'id', 'display' => 'title'));
        return View::make('frontend/videos/create', compact('data'));
    }

    public function postCreate()
    {
        if (!Sentry::getUser()->hasAnyAccess(['video', 'video.edit']))
            return View::make('backend/notallow');
        $data = Input::get('data');
        $rules = array('title' => 'required', 'youtube' => 'required');
        $validation = Validator::make($data['Video'], $rules);
        if ($validation->fails())
            return Redirect::back()->withInput()->withErrors($validation);
//        if (!empty($data['Video']['id']))
        $data['Video']['user_id'] = Sentry::getUser()->id;
        $data['Video']['status'] = 'published';
        $myModel = new MyModel();
        $video = $myModel->saveItem('Video', $data['Video'], array('return' => 'class'));
        if (isset($data['Topics'])) {
            $video->topics()->detach();
            $video->topics()->attach($data['Topics']);
        }
        if (isset($data['Tags']) && !empty($data['Tags'])) {
            $tags = explode(',', $data['Tags']);
            foreach ($tags as $tag) {
                $tag_id = \Tag::Check($tag);
                $video->tags()->attach($tag_id);
            }
        }
        return Redirect::route('update/video/admin', $video->id)->with('success', 'Hợp âm đã được lưu');
    }
}

